package com.code.generate.controller;


import com.code.generate.model.Project;
import com.code.generate.util.JsonRecordUtil;
import com.code.generate.vo.ResultData;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@Slf4j
@RestController
@RequestMapping("/project")
public class ProjectController{
    @RequestMapping(value = "/list", method = {RequestMethod.POST,RequestMethod.GET})
    public ResultData list() {
        List<Record> list =Db.use().find("select project.project_id projectId,project.jdbc_config_id jdbcConfigId,project.`name`,jdbc_config.name jdbcName from project LEFT JOIN jdbc_config on project.jdbc_config_id=jdbc_config.jdbc_config_id order by project.project_id asc");
        List listData = JsonRecordUtil.convertRecords(list);
        return ResultData.buildSuccess(listData);
    }
    @RequestMapping(value = "/del", method = {RequestMethod.POST,RequestMethod.GET})
    public ResultData del(@RequestParam("id")String id) {
        Project.dao.deleteById(id);
        return ResultData.buildSuccess();
    }
    @RequestMapping(value = "/get", method = {RequestMethod.POST,RequestMethod.GET})
    public ResultData get(@RequestParam("id")String id) {
        return ResultData.buildSuccess(Project.dao.findById(id));
    }

    @RequestMapping(value = "/saveUpdate", method = {RequestMethod.POST,RequestMethod.GET})
    public ResultData saveUpdate(@RequestParam(value = "name",required = true)String name,
                                 @RequestParam(value = "jdbcConfigId",required = true)Integer jdbcConfigId,
                                 @RequestParam(value = "projectId",required = false)Integer projectId) {
        Project project = new Project();
        project.setName(name);
        if (jdbcConfigId != null) {
            project.setJdbcConfigId(jdbcConfigId);
        }
        if (projectId == null) {
            project.save();
        } else {
            project.setProjectId(projectId);
            project.update();
        }

        return ResultData.buildSuccess();
    }
}